package conf

import (
	"fmt"
	"os"
	"path/filepath"
)

// 寻找mod文件
func hasGoMod(path string) bool {
	goModPath := filepath.Join(path, "go.mod")
	if _, err := os.Stat(goModPath); err == nil {
		return true
	}
	return false
}

// 寻找项目根目录
func getProjectRoot() (string, error) {
	currentPath, err := os.Getwd()
	if err != nil {
		return "", err
	}
	for {
		if hasGoMod(currentPath) {
			return currentPath, nil
		}
		parent := filepath.Dir(currentPath)
		if parent == currentPath {
			break
		}
		currentPath = parent
	}
	return "", fmt.Errorf("go module not found in the current directory or any parent directory")
}

// 返回项目路径的函数
func ReturnRootPath() string {
	rootPath, err := getProjectRoot()
	if err != nil {
		panic(err)
	}
	return rootPath
}
